package chabernac.android.wordbattle.paint.boggle;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import android.graphics.Color;
import chabernac.android.wordbattle.model.Word;
import chabernac.android.wordbattle.model.WordRaster;
import chabernac.android.wordbattle.paint.ClearAllDrawable;
import chabernac.android.wordbattle.paint.DrawableComposite;
import chabernac.android.wordbattle.paint.iDrawable;
import chabernac.android.wordbattle.paint.iDrawableFactory;

public class BoggleStyleDrawableFactory implements iDrawableFactory {
  private static Set<Integer> USED_COLORS = new HashSet<Integer>();
  private static Random RANDOM = new Random();
  
  private final Map<Word, iDrawable> myWordDrawables = new HashMap<Word, iDrawable>();
  
  private iDrawable mySelectedWordsDrawable = null;
  private iDrawable myClearAllDraweble = null;
  private iDrawable myWordRasterDrawable = null;

  public BoggleStyleDrawableFactory() {
    super();
  }

  private iDrawable createWordDrawable(Word aWord) {
    if(!myWordDrawables.containsKey(aWord)){
      myWordDrawables.put(aWord, new BoggleSelectedLettersPictureDrawable(aWord, getRandomColor()));
    }
    return myWordDrawables.get(aWord);
  }

  private iDrawable createSelectedLettersDrawable(Word aWord) {
    return new BoggleSelectedLettersPictureDrawable(aWord, getRandomColor());
  }
  

  private static int randomColor(){
    return 50 + Math.abs(RANDOM.nextInt() % 5) * 40;
  }

  protected static int getRandomColor( ) {
    int theRandomColor = Color.rgb( randomColor(), randomColor(), randomColor()); 
    while(USED_COLORS.contains(theRandomColor)){
      theRandomColor = Color.rgb( randomColor(), randomColor(), randomColor());
    }
    USED_COLORS.add(theRandomColor);
    return theRandomColor;
  }

  private iDrawable createSelectedWordsDrawable(WordRaster aRaster) {
    if(mySelectedWordsDrawable == null){
      mySelectedWordsDrawable = new BoggleSelectedWordsBitmapDrawable();
    }
    return mySelectedWordsDrawable;
  }

  @Override
  public iDrawable createGameDrawable( WordRaster aRaster ) {
    DrawableComposite theComposite = new DrawableComposite();
    
    theComposite.addDrawable( createClearAllDrawable() );
    theComposite.addDrawable( createWordRasterDrawable( aRaster ));
    theComposite.addDrawable( createSelectedWordsDrawable(aRaster) );
    
    return theComposite;
  }

  public iDrawable createWordRasterDrawable( WordRaster aRaster ) {
    if(myWordRasterDrawable == null) {
      myWordRasterDrawable = new BoggleWordRasterDrawable( aRaster );
    }
    return myWordRasterDrawable;
  }

  private iDrawable createClearAllDrawable() {
    if(myClearAllDraweble == null){
      myClearAllDraweble = new ClearAllDrawable(  Color.LTGRAY );
    }
    return myClearAllDraweble;
  }
}
